<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button v-hasPerm="['/admin/common/area/add']" type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
          <el-button :disabled="selectIds.length === 0" v-hasPerm="'/admin/common/area/del'" type="danger" icon="delete"
            @click="handleDelete()">
            删除
          </el-button>
        </div>
      </div>
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="片区id" prop="id" width="80" />
        <el-table-column label="区域名称" prop="name" />
        <el-table-column align="center" fixed="right" label="操作" width="250">
          <template #default="scope">
            <el-button v-hasPerm="'/admin/common/area/update'" type="primary" size="small" link icon="edit"
              @click="handleOpenDialog(scope.row)">
              修改
            </el-button>
            <el-button v-hasPerm="'/admin/common/area/del'" type="danger" icon="delete" link size="small"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery()" />
    </el-card>

    <!-- 片区表单 -->
    <el-dialog :close-on-click-modal="false" v-model="dialog.visible" :title="dialog.title" append-to-body
      @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="片区名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入片区名称" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Area",
  inheritAttrs: false,
});

import areaAPI, { Form, PageVO, areaPageQuery } from "@/api/waterMeter/area";

const pageData = ref<PageVO[]>([]);
const formRef = ref(ElForm);
const loading = ref(false);
const total = ref(0);

const queryParams = reactive<areaPageQuery>({
  page: 1,
  ps: 10,
});

const dialog = reactive({
  visible: false,
  title: "新增片区",
});

// 选中的ID
const selectIds = ref<number[]>([]);

const formData = reactive<Form>({
  name: '',
  // 手机号
  tel: '',
  // 密码
  login_secret: ''
});

const rules = reactive({
  name: [{ required: true, message: "抄表员姓名不能为空", trigger: "blur" }],
  tel: [{ required: true, message: "手机号，用来登录抄表员终端", trigger: "blur" }],
  login_secret: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

/**
 * 打开弹窗
 *
 * @param id 片区ID
 */
async function handleOpenDialog(data?: any) {
  dialog.visible = true;
  if (data) {
    Object.assign(formData, { ...data });
    dialog.title = "修改片区";
  } else {
    dialog.title = "新增片区";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();

  formData.id = undefined;
}


// 提交表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (formData.id) {
        areaAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        areaAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);


// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 删除片区
 *
 * @param id  片区ID
 */
function handleDelete(id?: number) {
  let delIds = id ? [id] : selectIds.value;
  if (!delIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除片区?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      areaAPI.deleteByIds({ ids: delIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/** 查询通知公告 */
function handleQuery() {
  loading.value = true;
  areaAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置通知公告查询 */
function handleResetQuery() {
  formRef.value!.resetFields();
  queryParams.page = 1;
  handleQuery();
}

onMounted(() => {
  handleQuery();
});
</script>
